/*
 * Copyright 2011 Subhabrata Ghosh <subho.ghosh at langene.net>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */



package net.langene.nlp.scripts;

//~--- non-JDK imports --------------------------------------------------------

import net.langene.nlp.Context;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//~--- JDK imports ------------------------------------------------------------

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

//~--- classes ----------------------------------------------------------------

/**
 *
 * @author Subhabrata Ghosh <subho.ghosh at langene.net>
 */
public class DBSetup {
    private static Logger	_logger = LoggerFactory.getLogger(DBSetup.class);

    //~--- methods ------------------------------------------------------------

    /**
     * Check to see if the local DB has been installed.
     * 
     * @throws Exception
     */
    public static void checkAndInstallDB() throws Exception {
        Connection	dbconn = Context.get().getConnection();

        if (!checkSchemaExists(dbconn)) {
            createSchema(dbconn);
        }
    }

    private static void createSchema(Connection dbconn) throws Exception {
        InputStream	is =
            DBSetup.class.getResourceAsStream("/net/langene/nlp/scripts/create-schema.sql");
        StringBuilder	buffer = new StringBuilder();
        BufferedReader	br     = new BufferedReader(new InputStreamReader(is));

        while (true) {
            String	line = br.readLine();

            if (line == null) {
                break;
            }

            if (line.isEmpty()) {
                continue;
            }

            if (line.trim().startsWith("--")) {
                continue;
            }

            buffer.append(line);
        }

        String[]	strstmnts = buffer.toString().split(";");

        if ((strstmnts == null) || (strstmnts.length <= 0)) {
            throw new Exception("Invalid SQL Script specified. No Statements found.");
        }

        Statement	ddl = dbconn.createStatement();

        for (String strstmnt : strstmnts) {
            _logger.debug("Running DLL : [" + strstmnt + "]");
            ddl.execute(strstmnt);
        }

        ddl.close();
    }

    private static boolean checkSchemaExists(Connection dbconn) throws Exception {
        String		sqlstr = "SELECT schema_name FROM information_schema.SCHEMATA";
        Statement	stmnt  = dbconn.createStatement();
        ResultSet	rs     = stmnt.executeQuery(sqlstr);

        try {
            while (rs.next()) {
                String	scname = rs.getString(1);

                if (scname.compareToIgnoreCase("langene_nlp") == 0) {
                    _logger.debug("DB Schema [" + scname + "] found...");

                    return true;
                }
            }

            _logger.debug("HSQLDB Schema not found...");

            return false;
        } finally {
            rs.close();
            stmnt.close();
        }
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
